package com.luo.backend.controller;

import com.luo.backend.common.ApiResponse;
import com.luo.backend.dto.*;
import com.luo.backend.service.AuthService;
import com.luo.backend.service.EmailVerificationService;
import com.luo.backend.util.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * 认证控制器
 */
@RestController
@RequestMapping("/api/v1/auth")
public class AuthController {
    
    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);
    
    @Autowired
    private AuthService authService;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @Autowired
    private EmailVerificationService emailVerificationService;
    
    /**
     * 用户注册
     */
    @PostMapping("/register")
    public ApiResponse<AuthResponse> register(@Valid @RequestBody RegisterRequest request) {
        try {
            logger.info("收到用户注册请求: {}", request.getUsername());
            AuthResponse response = authService.register(request);
            return ApiResponse.created("注册成功", response);
        } catch (Exception e) {
            logger.error("用户注册失败", e);
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 用户登录
     */
    @PostMapping("/login")
    public ApiResponse<AuthResponse> login(@Valid @RequestBody LoginRequest request) {
        try {
            logger.info("收到用户登录请求: {}", request.getUsername());
            AuthResponse response = authService.login(request);
            return ApiResponse.success("登录成功", response);
        } catch (Exception e) {
            logger.error("用户登录失败", e);
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 获取用户信息
     */
    @GetMapping("/profile")
    public ApiResponse<UserResponse> getProfile(HttpServletRequest request) {
        try {
            Long userId = getCurrentUserId(request);
            UserResponse user = authService.getUserById(userId);
            return ApiResponse.success(user);
        } catch (Exception e) {
            logger.error("获取用户信息失败", e);
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 更新用户信息
     */
    @PutMapping("/profile")
    public ApiResponse<UserResponse> updateProfile(
            @Valid @RequestBody UpdateUserRequest updateRequest,
            HttpServletRequest request) {
        logger.info("收到更新用户信息请求");
        try {
            logger.info("开始获取用户ID");
            Long userId = getCurrentUserId(request);
            logger.info("获取到用户ID: {}", userId);
            
            logger.info("开始更新用户信息: realName={}, phone={}, avatar={}", 
                updateRequest.getRealName(), updateRequest.getPhone(), updateRequest.getAvatar());
            UserResponse user = authService.updateUser(userId, updateRequest);
            logger.info("用户信息更新成功");
            
            return ApiResponse.success("更新成功", user);
        } catch (Exception e) {
            logger.error("更新用户信息失败", e);
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 发送邮箱验证码
     */
    @PostMapping("/email/send-code")
    public ApiResponse<SendCodeResponse> sendEmailCode(
            @Valid @RequestBody SendCodeRequest request,
            HttpServletRequest httpRequest) {
        try {
            logger.info("发送验证码请求 - email: {}, type: {}", request.getEmail(), request.getType());
            SendCodeResponse response = emailVerificationService.sendVerificationCode(
                request.getEmail(), request.getType(), httpRequest);
            return ApiResponse.success("验证码已发送", response);
        } catch (Exception e) {
            logger.error("发送验证码失败", e);
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 验证邮箱验证码
     */
    @PostMapping("/email/verify-code")
    public ApiResponse<Boolean> verifyEmailCode(@Valid @RequestBody VerifyCodeRequest request) {
        try {
            logger.info("验证验证码请求 - email: {}, type: {}", request.getEmail(), request.getType());
            boolean valid = emailVerificationService.verifyCode(
                request.getEmail(), request.getCode(), request.getType());
            
            if (valid) {
                return ApiResponse.success("验证成功", true);
            } else {
                return ApiResponse.error("验证码错误或已过期");
            }
        } catch (Exception e) {
            logger.error("验证验证码失败", e);
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 修改密码（已登录用户）
     */
    @PutMapping("/password")
    public ApiResponse<String> changePassword(
            @Valid @RequestBody ChangePasswordRequest request,
            HttpServletRequest httpRequest) {
        try {
            Long userId = getCurrentUserId(httpRequest);
            logger.info("修改密码请求 - userId: {}", userId);
            
            authService.changePassword(userId, request.getOldPassword(), request.getNewPassword());
            return ApiResponse.success("密码修改成功", null);
        } catch (Exception e) {
            logger.error("修改密码失败", e);
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 重置密码（忘记密码）
     */
    @PostMapping("/password/reset")
    public ApiResponse<String> resetPassword(@Valid @RequestBody ResetPasswordRequest request) {
        try {
            logger.info("重置密码请求 - email: {}", request.getEmail());
            authService.resetPassword(request.getEmail(), request.getCode(), request.getNewPassword());
            return ApiResponse.success("密码重置成功", null);
        } catch (Exception e) {
            logger.error("重置密码失败", e);
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 修改邮箱
     */
    @PutMapping("/email")
    public ApiResponse<UserResponse> changeEmail(
            @Valid @RequestBody ChangeEmailRequest request,
            HttpServletRequest httpRequest) {
        try {
            Long userId = getCurrentUserId(httpRequest);
            logger.info("修改邮箱请求 - userId: {}, newEmail: {}", userId, request.getNewEmail());
            
            UserResponse userResponse = authService.changeEmail(
                userId, request.getNewEmail(), request.getCode(), request.getPassword());
            return ApiResponse.success("邮箱修改成功", userResponse);
        } catch (Exception e) {
            logger.error("修改邮箱失败", e);
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 从安全上下文中获取当前用户ID
     */
    private Long getCurrentUserId(HttpServletRequest request) {
        // 从Spring Security上下文中获取用户ID
        Object principal = org.springframework.security.core.context.SecurityContextHolder.getContext()
                .getAuthentication().getPrincipal();
        
        if (principal instanceof Long) {
            return (Long) principal;
        }
        
        throw new RuntimeException("未能获取当前用户信息");
    }
}
